﻿using System;
using System.Web.Mvc;
using GabageFactory.Models;
using GabageFactory.Utiliy.Crypt;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Collections.Generic;
using System.Text;

namespace GabageFactory.Controllers
{
    [Authorize]
    public class GraphController : BaseController
    {
        private FactoryWeatherReposity weatherReposity;

        private StackReposity stackReposity;

        private TailingpondReposity tailingpondReposity;

        private static string[] weatherGraphs = new string[] {"降水量及蒸发量", "最高温度及最低温度"};

                       
        private string[] stackGraphs = new string[] 
        {
             "堆场一区水位～时间",
             "堆场一区PH值～时间", 
             "堆场一区水量～时间",
             "堆场二区水位～时间",
             "堆场二区PH值～时间",
             "堆场二区水量～时间",
             "调节水池水位～时间",
             "调节水池PH值～时间",
             "调节水池水量～时间",
             "集水井水位～时间",
             "集水井PH值～时间",
             "下游河流水位～时间",
             "下游河流PH值～时间",
             "下游河流总磷含量～时间",
             "下游河流总氟含量～时间",
             "进浆量～时间",
             "回水量～时间",
             "磷石膏坝外堤最低点及最高高程～时间",
             "安全超高",
             "沉积滩最小及最大宽度～时间",
             "测压井水头～时间",
             "水力梯度～时间",
             "测压仪～时间"
        };

        private string[] tailingpondGraphs = new string[] 
        { 
            "库区水位～时间",
            "库区水量～时间",
            "调节水池水位～时间",
            "调节水池水量～时间",
            "下游河流水位～时间",
            "进浆量～时间",
            "回水量～时间",
            "堆积坝高程～时间",
            "堆积坝宽度～时间",
            "干滩长度～时间",
            "安全超高～时间"
        };

        public enum GraphType
        {
            Weather,
            Stack,
            Tailingpond
        }

        public GraphController()
        {
            weatherReposity = new FactoryWeatherReposity();
            stackReposity = new StackReposity();
            tailingpondReposity = new TailingpondReposity();
        }

        //
        // GET: /User/

        public ActionResult Tailingpond()
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Analyzer);
            roles.Add(RoleEnum.Expert);
            roles.Add(RoleEnum.Manager);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Recorder);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            ViewData["showFactory"] = false;
            ViewData["showStacks"] = false;
            ViewData["stacksAndTailingponds"] = new List<SelectListItem>();
            ViewData["factoryId"] = GetCurrentUser().FactoryId;

            if (GetCurrentUser().RoleId == (int)RoleEnum.Analyzer || GetCurrentUser().RoleId == (int)RoleEnum.Expert)
            {
                ShowFactoryList(0);
                List<SelectListItem> factories = (List<SelectListItem>)ViewData["factories"];
                SelectListItem item1 = null;
                foreach (SelectListItem item in factories)
                {
                    if (item.Value == "3")
                    {
                        item1 = item;
                        break;
                    }
                }
                if (item1 != null)
                {
                    factories.Remove(item1);
                }
                ViewData["factories"] = factories;
                ViewData["showFactory"] = true;
            }
            else
            {
                int showType = 2;
                ShowStackAndTailingoind(GetCurrentUser().FactoryId, showType);
            }

            ViewData["showStacks"] = true;


            ShowGraphType(GraphType.Tailingpond, 1);

            ViewData["showChart"] = false;
            return View();
        }
        
        //
        // GET: /User/

        public ActionResult Index(GraphType graphType)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Analyzer);
            roles.Add(RoleEnum.Expert);
            roles.Add(RoleEnum.Manager);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Recorder);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            ViewData["showFactory"] = false;
            ViewData["showStacks"] = false;
            ViewData["stacksAndTailingponds"] = new List<SelectListItem>();
            ViewData["factoryId"] = GetCurrentUser().FactoryId;
            
            if (GetCurrentUser().RoleId == (int)RoleEnum.Analyzer || GetCurrentUser().RoleId == (int)RoleEnum.Expert)
            {
                ShowFactoryList(0);
                List<SelectListItem> factories = (List<SelectListItem>)ViewData["factories"];
                SelectListItem item1 = null;
                foreach (SelectListItem item in factories)
                {
                    if (item.Value == "3")
                    {
                        item1 = item;
                        break;
                    }
                }
                if (item1 != null)
                {
                    factories.Remove(item1);
                }
                ViewData["factories"] = factories;
                ViewData["showFactory"] = true;
            }
            else
            {
                int showType = 0;

                if (graphType == GraphType.Stack)
                    showType = 1;
                else if (graphType == GraphType.Tailingpond)
                    showType = 2;
                ShowStackAndTailingoind(GetCurrentUser().FactoryId, showType);
            }

            if (graphType != GraphType.Weather)
            {
                ViewData["showStacks"] = true;
            }

            ViewData["graphType"] = graphType;

            ShowGraphType(graphType, 1);

            ViewData["showChart"] = false;
            return View();
        }

        [HttpPost]
        public ActionResult Index(GraphType graphType, FormCollection collection)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Analyzer);
            roles.Add(RoleEnum.Expert);
            roles.Add(RoleEnum.Manager);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Recorder);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            ViewData["showFactory"] = false;
            ViewData["showStacks"] = false;
            ViewData["id"] = 1;
            ViewData["stacksAndTailingponds"] = new List<SelectListItem>();
            int factoryId = parseInt(collection.Get("factoryId"));
            int stackId = parseInt(collection.Get("stackId"));
            ViewData["factoryId"] = factoryId;

            if (GetCurrentUser().RoleId == (int)RoleEnum.Analyzer || GetCurrentUser().RoleId == (int)RoleEnum.Expert)
            {
                ShowFactoryList(factoryId);
                ViewData["showFactory"] = true;
            }
            else
            {
                int showType = 0;

                if (graphType == GraphType.Stack)
                    showType = 1;
                else if (graphType == GraphType.Tailingpond)
                    showType = 2;
                ShowStackAndTailingoind(factoryId, showType, stackId);
            }

            if (graphType != GraphType.Weather)
            {
                ViewData["showStacks"] = true;
                ViewData["id"] = parseInt(collection.Get("stackId"));
            }

            ViewData["graphType"] = graphType;
            int subGraphType = parseInt(collection.Get("subGraphType"));
            ViewData["subGraphType"] = subGraphType;

            int dateType = parseInt(collection.Get("dateType"));
            DateTime toDate = DateTime.Now.Date;
            DateTime fromDate = toDate.AddDays(-29);
            if (dateType == 2)
            {
                fromDate = DateTime.Parse(collection.Get("dateFrom"));
                toDate = DateTime.Parse(collection.Get("dateTo"));
            }
            else
            {
                int predefinedDate = parseInt(collection.Get("predefinedDate"));
                switch (predefinedDate)
                {
                    case 1:
                        fromDate = toDate.AddDays(-13);
                        break;
                    case 2:
                        fromDate = toDate.AddDays(-29);
                        break;
                    case 3:
                        fromDate = toDate.AddDays(-89);
                        break;
                    case 4:
                        fromDate = toDate.AddDays(-179);
                        break;
                    case 5:
                        fromDate = toDate.AddDays(-364);
                        break;
                    default:
                        fromDate = toDate.AddDays(-29);
                        break;
                }
            }
            if (toDate >= DateTime.Now.Date)
            {
                toDate = DateTime.Now.AddDays(-1);
            }
            ViewData["fromDate"] = fromDate.ToString("yyyy-MM-dd");
            ViewData["toDate"] = toDate.ToString("yyyy-MM-dd");
            ShowGraphType(graphType, subGraphType);

            ViewData["showChart"] = true;
            return View();
        }

        public ActionResult Display(int factoryId, int id, GraphType graphType, int subGraphType, DateTime fromDate, DateTime toDate)
        {
            HttpContext.Response.ContentEncoding = Encoding.UTF8;
            HttpContext.Response.ContentType = "text/xml;charset=utf-8";
            HttpContext.Response.Charset = "UTF-8";
            HttpContext.Response.BinaryWrite(new byte[] { 0xEF, 0xBB, 0xBF }); 
            
            if (graphType == GraphType.Weather)
            {
                DisplayWeatherGraph(factoryId, subGraphType, fromDate, toDate);
            }
            else if (graphType == GraphType.Stack)
            {
                DisplayStackGraph(factoryId, id, subGraphType, fromDate, toDate);
            }
            else if (graphType == GraphType.Tailingpond)
            {
                DisplayTailingpondGraph(factoryId, id, subGraphType, fromDate, toDate);
            }

            return View();
        }

        private void DisplayWeatherGraph(int factoryId, int subGraphType, DateTime fromDate, DateTime toDate)
        {
            fromDate = fromDate.Date;
            toDate = toDate.Date.AddDays(1);
            List<string> dates = new List<string>();
            IDictionary<string, List<float>> values = new Dictionary<string, List<float>>();
            IDictionary<DateTime, Factory_daily_weather_info> infos = weatherReposity.QueryWeathers(factoryId, fromDate, toDate);
            if (subGraphType == 1)
            {
                List<float> rainfalls = new List<float>();
                List<float> evaporations = new List<float>();
                for (; fromDate < toDate; fromDate =fromDate.AddDays(1))
                {
                    
                    Factory_daily_weather_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.rainfall_capacity.HasValue && info.evaporation_capacity.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            rainfalls.Add(info.rainfall_capacity.Value);
                            evaporations.Add(info.evaporation_capacity.Value);
                        }
                    }
                }
                values.Add("降雨量（毫米）", rainfalls);
                values.Add("蒸发量（毫米）", evaporations);
            }
            else if (subGraphType == 2)
            {
                List<float> hightemps = new List<float>();
                List<float> lowtemps = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    Factory_daily_weather_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.highest_temperature.HasValue && info.lowest_temperature.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            hightemps.Add(info.highest_temperature.Value);
                            lowtemps.Add(info.lowest_temperature.Value);
                        }
                    }
                }
                values.Add("最高温度（℃）", hightemps);
                values.Add("最低温度（℃）", lowtemps);
            }

            ViewData["minValue"] = GetMinValue(values);
            ViewData["dates"] = dates;
            ViewData["values"] = values;
        }

        private void DisplayStackGraph(int factoryId, int stackId, int subGraphType, DateTime fromDate, DateTime toDate)
        {
            fromDate = fromDate.Date;
            toDate = toDate.Date.AddDays(1);
            List<string> dates = new List<string>();
            IDictionary<string, List<float>> values = new Dictionary<string, List<float>>();
            StackWaterReposity stackWaterReposity = new StackWaterReposity();
            IDictionary<DateTime, stack_daily_water_info> infos = stackWaterReposity.QueryDailyWaterInfo(stackId, fromDate, toDate);
            if (subGraphType == 1)
            {
                List<float> waterLevel = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.partition1_water_level.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            waterLevel.Add(info.partition1_water_level.Value);
                        }
                    }
                }
                values.Add("堆场一区水位（米）", waterLevel);
            }
            else if (subGraphType == 2)
            {
                List<float> waterPH = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.partition1_water_ph.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            waterPH.Add(info.partition1_water_ph.Value);
                        }
                    }
                }
                values.Add("堆场一区PH值", waterPH);
            }
            else if (subGraphType == 3)
            {
                List<float> waterPH = new List<float>();
                fromDate = Tools.GetWeeklyDate(fromDate);
                for (; fromDate < toDate; fromDate = fromDate.AddDays(7))
                {

                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.partition1_water_capacity.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            waterPH.Add(info.partition1_water_capacity.Value);
                        }
                    }
                }
                values.Add("堆场一区水量（万立方米）", waterPH);
            }
            else if (subGraphType == 4)
            {
                List<float> waterLevel = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.partition2_water_level.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            waterLevel.Add(info.partition2_water_level.Value);
                        }
                    }
                }
                values.Add("堆场二区水位（米）", waterLevel);
            }
            else if (subGraphType == 5)
            {
                List<float> waterPH = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.partition2_water_ph.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            waterPH.Add(info.partition2_water_ph.Value);
                        }
                    }
                }
                values.Add("堆场二区PH值", waterPH);
            }
            else if (subGraphType == 6)
            {
                List<float> waterPH = new List<float>();
                fromDate = Tools.GetWeeklyDate(fromDate);
                for (; fromDate < toDate; fromDate = fromDate.AddDays(7))
                {
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.partition2_water_capacity.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            waterPH.Add(info.partition2_water_capacity.Value);
                        }
                    }
                }
                values.Add("堆场二区水量（万立方米）", waterPH);
            }
            else if (subGraphType == 7)
            {
                PoolReposity poolReposity = new PoolReposity();
                IEnumerable<Return_Water_Pond_Base_Info> pools = poolReposity.ListPools(stackId);
                DateTime originalDate = fromDate.Date;
                foreach (Return_Water_Pond_Base_Info pool in pools)
                {
                    IDictionary<DateTime, stack_pool_daily_water_info> poolInfos = stackWaterReposity.QueryPoolDailyWaterInfo(stackId, pool.pond_no, fromDate, toDate);
                    List<float> waterLevel = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        stack_pool_daily_water_info info = null;
                        if (poolInfos.TryGetValue(fromDate, out info))
                        {
                            if (info.pool_water_level.HasValue)
                            {
                                dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                waterLevel.Add(info.pool_water_level.Value);
                            }
                        }
                    }
                    fromDate = originalDate.Date;
                    values.Add(pool.pond_no + "号调节水池水位（米）", waterLevel);
                }
            }
            else if (subGraphType == 8)
            {
                PoolReposity poolReposity = new PoolReposity();
                IEnumerable<Return_Water_Pond_Base_Info> pools = poolReposity.ListPools(stackId);
                foreach (Return_Water_Pond_Base_Info pool in pools)
                {
                    IDictionary<DateTime, stack_pool_daily_water_info> poolInfos = stackWaterReposity.QueryPoolDailyWaterInfo(stackId, pool.pond_no, fromDate, toDate);
                    List<float> waterPH = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        stack_pool_daily_water_info info = null;
                        if (poolInfos.TryGetValue(fromDate, out info))
                        {
                            if (info.pool_water_ph.HasValue)
                            {
                                if (!dates.Contains(fromDate.ToString("yyyy-MM-dd"))) dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                waterPH.Add(info.pool_water_ph.Value);
                            }
                        }
                    }
                    values.Add(pool.pond_no + "号调节水池PH值", waterPH);
                }
            }
            else if (subGraphType == 9)
            {
                PoolReposity poolReposity = new PoolReposity();
                IEnumerable<Return_Water_Pond_Base_Info> pools = poolReposity.ListPools(stackId);
                foreach (Return_Water_Pond_Base_Info pool in pools)
                {
                    IDictionary<DateTime, stack_pool_daily_water_info> poolInfos = stackWaterReposity.QueryPoolDailyWaterInfo(stackId, pool.pond_no, fromDate, toDate);
                    List<float> waterPH = new List<float>();
                    fromDate = Tools.GetWeeklyDate(fromDate);
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(7))
                    {
                        stack_pool_daily_water_info info = null;
                        if (poolInfos.TryGetValue(fromDate, out info))
                        {
                            if (info.pool_water_capacity.HasValue)
                            {
                                if (!dates.Contains(fromDate.ToString("yyyy-MM-dd"))) dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                waterPH.Add(info.pool_water_capacity.Value);
                            }
                        }
                    }
                    values.Add(pool.pond_no + "号调节水池水量（万立方米）", waterPH);
                }
            }
            else if (subGraphType == 10)
            {
                List<float> waterLevel = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.catchpit_water_level.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            waterLevel.Add(info.catchpit_water_level.Value);
                        }
                    }
                }
                values.Add("集水井水位（米）", waterLevel);
            }
            else if (subGraphType == 11)
            {
                List<float> waterPH = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.catchpit_water_ph.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            waterPH.Add(info.catchpit_water_ph.Value);
                        }
                    }
                }
                values.Add("集水井PH值", waterPH);
            }
            else if (subGraphType == 12)
            {
                List<float> waterLevel = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if(info.downstream_water_level.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            waterLevel.Add(info.downstream_water_level.Value);
                        }
                    }
                }
                values.Add("下游河流水位（米）", waterLevel);
            }
            else if (subGraphType == 13)
            {
                List<float> waterPH = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if(info.downstream_water_ph.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            waterPH.Add(info.downstream_water_ph.Value);
                        }
                    }
                }
                values.Add("下游河流PH值", waterPH);
            }
            else if (subGraphType == 14)
            {
                List<float> totalPhosphorus = new List<float>();
                fromDate = Tools.GetWeeklyDate(fromDate);
                for (; fromDate < toDate; fromDate = fromDate.AddDays(7))
                {
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if(info.total_down_phosphorus.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            totalPhosphorus.Add(info.total_down_phosphorus.Value);
                        }
                    }
                }
                values.Add("下游总磷含量（ppm）", totalPhosphorus);
            }
            else if (subGraphType == 15)
            {
                List<float> totalFluorin = new List<float>();
                fromDate = Tools.GetWeeklyDate(fromDate);
                for (; fromDate < toDate; fromDate = fromDate.AddDays(7))
                {
                    stack_daily_water_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.total_down_fluorin.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            totalFluorin.Add(info.total_down_fluorin.Value);
                        }
                    }
                }
                values.Add("下游总氟含量（ppm）", totalFluorin);
            }
            else if (subGraphType == 16)
            {
                StackBackWaterReposity stackBackWaterReposity = new StackBackWaterReposity();
                IDictionary<DateTime, stack_backwater_info> backwateInfos = stackBackWaterReposity.QueryBackWaterInfo(stackId, fromDate, toDate);
                List<float> flow = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    stack_backwater_info info = null;
                    if (backwateInfos.TryGetValue(fromDate, out info))
                    {
                        if(info.flow_amount.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            flow.Add(info.flow_amount.Value);
                        }
                    }
                }
                values.Add("进浆量（万立方米/天）", flow);
            }
            else if (subGraphType == 17)
            {
                StackBackWaterReposity stackBackWaterReposity = new StackBackWaterReposity();
                IDictionary<DateTime, stack_backwater_info> backwateInfos = stackBackWaterReposity.QueryBackWaterInfo(stackId, fromDate, toDate);
                List<float> backwater = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    stack_backwater_info info = null;
                    if (backwateInfos.TryGetValue(fromDate, out info))
                    {
                        if (info.back_water.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            backwater.Add(info.back_water.Value);
                        }
                    }
                }
                values.Add("回水量（万立方米/天）", backwater);
            }
            else if (subGraphType == 18)
            {
                StackArdealiteReposity stackArdealiteReposity = new StackArdealiteReposity();
                IDictionary<DateTime, stack_ardealite_ditch> ardealiteInfos = stackArdealiteReposity.QueryArdealiteInfo(stackId, fromDate, toDate);
                List<float> bottomEls = new List<float>();
                List<float> topEls = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    
                    stack_ardealite_ditch info = null;
                    if (ardealiteInfos.TryGetValue(fromDate, out info))
                    {
                        if (info.dyke_bottom_El.HasValue && info.dyke_top_El.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            bottomEls.Add(info.dyke_bottom_El.Value);
                            topEls.Add(info.dyke_top_El.Value);
                        }
                    }
                }
                values.Add("最低点高程（米）", bottomEls);
                values.Add("最高点高程（米）", topEls);
            }
            else if (subGraphType == 19)
            {
                StackArdealiteReposity stackArdealiteReposity = new StackArdealiteReposity();
                IDictionary<DateTime, stack_ardealite_ditch> ardealiteInfos = stackArdealiteReposity.QueryArdealiteInfo(stackId, fromDate, toDate);
                List<float> safeHeights = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {

                    stack_ardealite_ditch info = null;
                    if (ardealiteInfos.TryGetValue(fromDate, out info))
                    {
                        if (info.safe_height.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            safeHeights.Add(info.safe_height.Value);
                        }
                    }
                }
                values.Add("安全超高（米）", safeHeights);
            }
            else if (subGraphType == 20)
            {
                StackArdealiteReposity stackArdealiteReposity = new StackArdealiteReposity();
                IDictionary<DateTime, stack_ardealite_ditch> ardealiteInfos = stackArdealiteReposity.QueryArdealiteInfo(stackId, fromDate, toDate);
                List<float> minWidth = new List<float>();
                List<float> maxWidth = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    stack_ardealite_ditch info = null;
                    if (ardealiteInfos.TryGetValue(fromDate, out info))
                    {
                        if (info.precipitation_beach_min_width.HasValue && info.precipitation_beach_max_width.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            minWidth.Add(info.precipitation_beach_min_width.Value);
                            maxWidth.Add(info.precipitation_beach_max_width.Value);
                        }
                    }
                }
                values.Add("最小宽度（米）", minWidth);
                values.Add("最大宽度（米）", maxWidth);
            }
            else if (subGraphType == 21)
            {
                PiezometerRecordReposity piezometerRecordReposity = new PiezometerRecordReposity();
                PiezometerReposity piezometerReposity = new PiezometerReposity();
                IEnumerable<Piezometer_well_base_info> wells = piezometerReposity.ListWell(stackId);
                DateTime originalDate = fromDate.Date;
                foreach (Piezometer_well_base_info well in wells)
                {
                    IDictionary<DateTime, Piezometer_well_monthly_info> wellInfos = piezometerRecordReposity.QueryWellInfo(stackId, well.piezometer_well_id, fromDate, toDate);
                    List<float> els = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        Piezometer_well_monthly_info info = null;
                        if (wellInfos.TryGetValue(fromDate, out info))
                        {
                            if (info.Water_El.HasValue)
                            {
                                if (!dates.Contains(fromDate.ToString("yyyy-MM"))) dates.Add(fromDate.ToString("yyyy-MM"));
                                els.Add(info.Water_El.Value);
                            }
                        }
                    }
                    fromDate = originalDate.Date;
                    values.Add(well.piezometer_well_id + "号测压井水头（米）", els);
                }             
            }
            else if (subGraphType == 22)
            {
                PiezometerRecordReposity piezometerRecordReposity = new PiezometerRecordReposity();
                PiezometerReposity piezometerReposity = new PiezometerReposity();
                IEnumerable<Piezometer_base_info> equaps = piezometerReposity.ListEquaps(stackId);
                List<Piezometer_base_info> equapList = new List<Piezometer_base_info>();
                foreach (Piezometer_base_info equap in equaps)
                {
                    if (!equapList.Exists(item => item.piezometer_hole_id == equap.piezometer_hole_id))
                    {
                        equapList.Add(equap);
                    }
                }
                
                DateTime originalDate = fromDate.Date;
                foreach (Piezometer_base_info equap in equapList)
                {
                    IDictionary<DateTime, Piezometer_monthly_info> equapInfos = piezometerRecordReposity.QueryEquapInfo(stackId, equap.piezometer_hole_id, fromDate, toDate);
                    List<float> gradients = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        Piezometer_monthly_info info = null;
                        if (equapInfos.TryGetValue(fromDate, out info))
                        {
                            if (info.Hydraulic_gradient.HasValue)
                            {
                                if (!dates.Contains(fromDate.ToString("yyyy-MM"))) dates.Add(fromDate.ToString("yyyy-MM"));
                                gradients.Add(info.Hydraulic_gradient.Value);
                            }
                        }
                    }
                    fromDate = originalDate.Date;
                    values.Add("第" + equap.piezometer_hole_id + "组水力梯度", gradients);
                }
            }
            else if (subGraphType == 23)
            {
                PiezometerRecordReposity piezometerRecordReposity = new PiezometerRecordReposity();
                PiezometerReposity piezometerReposity = new PiezometerReposity();
                IEnumerable<Piezometer_base_info> equaps = piezometerReposity.ListEquaps(stackId);
                DateTime originalDate = fromDate.Date;
                foreach (Piezometer_base_info equap in equaps)
                {
                    IDictionary<DateTime, Piezometer_monthly_info> pressureInfos = piezometerRecordReposity.QueryEquapPressureInfo(stackId, equap.piezometer_hole_id, equap.piezometer_id, fromDate, toDate);
                    List<float> pressures = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        Piezometer_monthly_info info = null;
                        if (pressureInfos.TryGetValue(fromDate, out info))
                        {
                            if (info.gauge_Pressure_m.HasValue)
                            {
                                if (!dates.Contains(fromDate.ToString("yyyy-MM"))) dates.Add(fromDate.ToString("yyyy-MM"));
                                pressures.Add(info.gauge_Pressure_m.Value);
                            }
                        }
                    }
                    
                    fromDate = originalDate.Date;
                    values.Add("第" + equap.piezometer_hole_id + "组" + equap.piezometer_id + "号测压仪（米）", pressures);
                }
            }

            ViewData["minValue"] = GetMinValue(values);
            ViewData["dates"] = dates;
            ViewData["values"] = values;
        }

        private void DisplayTailingpondGraph(int factoryId, int tailingpondId, int subGraphType, DateTime fromDate, DateTime toDate)
        {
            
            fromDate = fromDate.Date;
            toDate = toDate.Date.AddDays(1);
            List<string> dates = new List<string>();
            IDictionary<string, List<float>> values = new Dictionary<string, List<float>>();

            if (subGraphType == 1 || subGraphType == 2 || subGraphType == 3 || subGraphType == 4 || subGraphType == 5)
            {
                TailingpondDailyWaterReposity tailingpondDailyWaterReposity = new TailingpondDailyWaterReposity();
                IDictionary<DateTime, tailingpond_daily_water_info> infos = tailingpondDailyWaterReposity.QueryWaterInfo(tailingpondId, fromDate, toDate);
                if (subGraphType == 1)
                {
                    List<float> reservoirs = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        tailingpond_daily_water_info info = null;
                        if (infos.TryGetValue(fromDate, out info))
                        {
                            if(info.reservoir_water_level.HasValue)
                            {
                                dates.Add(fromDate.ToString("yyyy-MM-dd")); 
                                reservoirs.Add(info.reservoir_water_level.Value);
                            }
                        }
                    }
                    values.Add("库区水位（米）", reservoirs);
                }
                else if (subGraphType == 2)
                {
                    List<float> reservoirs = new List<float>();
                    fromDate = Tools.GetWeeklyDate(fromDate);
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(7))
                    {
                        tailingpond_daily_water_info info = null;
                        if (infos.TryGetValue(fromDate, out info))
                        {
                            if (info.reservoir_water_capacity.HasValue)
                            {
                                dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                reservoirs.Add(info.reservoir_water_capacity.Value);
                            }
                        }
                    }
                    values.Add("库区水量（万立方米）", reservoirs);
                }
                else if (subGraphType == 3)
                {
                    List<float> pools = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        tailingpond_daily_water_info info = null;
                        if (infos.TryGetValue(fromDate, out info))
                        {
                            if (info.pool_water_level.HasValue)
                            {
                                dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                pools.Add(info.pool_water_level.Value);
                            }
                        }
                    }
                    values.Add("调节水池水位（米）", pools);
                }
                else if (subGraphType == 4)
                {
                    List<float> pools = new List<float>();
                    fromDate = Tools.GetWeeklyDate(fromDate);
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(7))
                    {
                        tailingpond_daily_water_info info = null;
                        if (infos.TryGetValue(fromDate, out info))
                        {
                            if (info.pool_water_capacity.HasValue)
                            {
                                dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                pools.Add(info.pool_water_capacity.Value);
                            }
                        }
                    }
                    values.Add("调节水池水量（万立方米）", pools);
                }
                else if (subGraphType == 5)
                {
                    List<float> downstreams = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        tailingpond_daily_water_info info = null;
                        if (infos.TryGetValue(fromDate, out info))
                        {
                            if(info.downstream_water_level.HasValue)
                            {
                                dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                downstreams.Add(info.downstream_water_level.Value);
                            }
                        }
                    }
                    values.Add("下游河流水位（米）", downstreams);
                }
            }
            else if (subGraphType == 6)
            {
                TailingpondBackWaterReposity tailingpondBackWaterReposity = new TailingpondBackWaterReposity();
                IDictionary<DateTime, tailingpond_backwater_info> infos = tailingpondBackWaterReposity.QueryBackWaterInfo(tailingpondId, fromDate, toDate);

                List<float> flowAmounts = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    tailingpond_backwater_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if(info.flow_amount.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            flowAmounts.Add(info.flow_amount.Value);
                        }
                    }
                }
                values.Add("进浆量（万立方米/天）", flowAmounts);
            }
            else if (subGraphType == 7)
            {
                TailingpondBackWaterReposity tailingpondBackWaterReposity = new TailingpondBackWaterReposity();
                IDictionary<DateTime, tailingpond_backwater_info> infos = tailingpondBackWaterReposity.QueryBackWaterInfo(tailingpondId, fromDate, toDate);

                List<float> backWaters = new List<float>();
                for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                {
                    tailingpond_backwater_info info = null;
                    if (infos.TryGetValue(fromDate, out info))
                    {
                        if (info.back_water.HasValue)
                        {
                            dates.Add(fromDate.ToString("yyyy-MM-dd"));
                            backWaters.Add(info.back_water.Value);
                        }
                    }
                }
                values.Add("回水量（万立方米/天）", backWaters);
            }
            else if (subGraphType == 8 || subGraphType == 9 || subGraphType == 10 || subGraphType == 11)
            {
                TailingpondFilldamReposity tailingpondFilldamReposity = new TailingpondFilldamReposity();
                IDictionary<DateTime, tailingpond_daily_filldam_info> infos = tailingpondFilldamReposity.QueryFilldamInfo(tailingpondId, fromDate, toDate);
                if (subGraphType == 8)
                {
                    List<float> topEls = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        tailingpond_daily_filldam_info info = null;
                        if (infos.TryGetValue(fromDate, out info))
                        {
                            if (info.dike_top_El.HasValue)
                            {
                                dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                topEls.Add(info.dike_top_El.Value);
                            }
                        }
                    }
                    values.Add("堆积坝高程（米）", topEls);
                }
                else if (subGraphType == 9)
                {
                    List<float> topWidthes = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        tailingpond_daily_filldam_info info = null;
                        if (infos.TryGetValue(fromDate, out info))
                        {
                            if (info.dike_top_width.HasValue)
                            {
                                dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                topWidthes.Add(info.dike_top_width.Value);
                            }
                        }
                    }
                    values.Add("堆积坝宽度（米）", topWidthes);
                }
                else if (subGraphType == 10)
                {
                    List<float> tryShoalWidthes = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        tailingpond_daily_filldam_info info = null;
                        if (infos.TryGetValue(fromDate, out info))
                        {
                            if(info.dry_shoal_width.HasValue)
                            {
                                dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                tryShoalWidthes.Add(info.dry_shoal_width.Value);
                            }
                        }
                    }
                    values.Add("干滩长度（米）", tryShoalWidthes);
                }
                else if (subGraphType == 11)
                {
                    List<float> safeHeights = new List<float>();
                    for (; fromDate < toDate; fromDate = fromDate.AddDays(1))
                    {
                        tailingpond_daily_filldam_info info = null;
                        if (infos.TryGetValue(fromDate, out info))
                        {
                            if(info.safe_height.HasValue)
                            {
                                dates.Add(fromDate.ToString("yyyy-MM-dd"));
                                safeHeights.Add(info.safe_height.Value);
                            }
                        }
                    }
                    values.Add("安全超高（米）", safeHeights);
                }
            }

            ViewData["minValue"] = GetMinValue(values);
            ViewData["dates"] = dates;
            ViewData["values"] = values;
        }

        private float GetMinValue(IDictionary<string, List<float>> values)
        {
            float minValue = float.MaxValue;
            foreach (List<float> value in values.Values)
            {
                foreach (float item in value)
                {
                    minValue = item < minValue ? item : minValue;
                }

            }

            if (minValue >= float.MaxValue)
            {
                minValue = 0;
            }

            return minValue * 0.95f;
        }

        private void ShowGraphType(GraphType graphType, int subGraphType)
        {
            if (graphType == GraphType.Weather)
            {
                ShowWeatherGraphTypes();
                ViewData["graphName"] = weatherGraphs[subGraphType - 1];
            }
            else if(graphType == GraphType.Stack)
            {
                ShowStackGraphTypes();
                ViewData["graphName"] = stackGraphs[subGraphType - 1];
            }
            else if (graphType == GraphType.Tailingpond)
            {
                ShowTailingpondGraphTypes();
                ViewData["graphName"] = tailingpondGraphs[subGraphType - 1];
            }
        }

        private void ShowWeatherGraphTypes()
        {
            List<SelectListItem> graphTypes = new List<SelectListItem>();
            for (int i = 0; i < weatherGraphs.Length; i++)
            {
                graphTypes.Add(new SelectListItem { Text = weatherGraphs[i], Value = (i + 1).ToString(), Selected = false });
            }
            ViewData["graphTypes"] = graphTypes;
        }

        private void ShowStackGraphTypes()
        {
            List<SelectListItem> graphTypes = new List<SelectListItem>();

            User user = GetCurrentUser();
            List<int> excepted = new List<int>{1, 4, 7, 10, 12, 13, 14};
            bool hasPriviledge = (user.RoleId == (int)RoleEnum.Expert);
            for (int i = 0; i < stackGraphs.Length; i++)
            {
                if (hasPriviledge || !excepted.Contains(i))
                {
                    graphTypes.Add(new SelectListItem { Text = stackGraphs[i], Value = (i + 1).ToString(), Selected = false });
                }
            } 
            ViewData["graphTypes"] = graphTypes;
        }

        private void ShowTailingpondGraphTypes()
        {
            List<SelectListItem> graphTypes = new List<SelectListItem>();

            for (int i = 0; i < tailingpondGraphs.Length; i++)
            {
                graphTypes.Add(new SelectListItem { Text = tailingpondGraphs[i], Value = (i + 1).ToString(), Selected = false });
            } 
            ViewData["graphTypes"] = graphTypes;
        }
    }
}
